import { dialog, app, shell } from 'electron'
import EventRoute from '../EventRoute'
import store from '../../store/index'
const routers: EventRoute[] = []
import shortcutManager from '../../utils/shortcutManager'
const shortcuts = shortcutManager.getInstance()
import { isProcessRunningWin } from '../../utils/index'
import { is } from '@electron-toolkit/utils'

// 默认设置
function getDefaultApplicationSettings() {
  return {
    shortcuts: {
      evokeChortcut: '',
      isevokeChortcut: true,
      screenshotChortcut: '',
      isscreenshotChortcut: true,
      screenRecordingChortcut: '',
      isscreenRecordingChortcut: true,
      chatChortcut: '',
      ischatChortcut: true,
    },
    recordingPath: app.getPath('desktop')
  }
}

// 读取设置（用于初始化渲染端）
routers.push(
  new EventRoute('get-application-settings', async () => {
    const settings = (store.get('applicationSettings')) || getDefaultApplicationSettings()
    const def = getDefaultApplicationSettings()
    const merged = {
      shortcuts: { ...def.shortcuts, ...(settings.shortcuts || {}) },
      recordingPath: settings.recordingPath || def.recordingPath
    }
    return merged
  })
)

// 选择录屏保存目录（仅返回选择结果，不落库）
routers.push(
  new EventRoute('pick-recording-path', async () => {
    const result = await dialog.showOpenDialog({
      properties: ['openDirectory', 'createDirectory']
    })
    if (result.canceled || !result.filePaths?.length) return null
    return result.filePaths[0]
  })
)

// 保存录屏目录（立即持久化）
routers.push(
  new EventRoute('save-recording-path', async (_api, { data }) => {
    const path = (data && data.path) || ''
    const prev = (store.get('applicationSettings')) || getDefaultApplicationSettings()
    store.set('applicationSettings', {
      shortcuts: prev.shortcuts || getDefaultApplicationSettings().shortcuts,
      recordingPath: path || prev.recordingPath || getDefaultApplicationSettings().recordingPath
    })
    return { success: true }
  })
)

// 保存快捷键（立即持久化）
routers.push(
  new EventRoute('save-application-shortcut', async (api, { data }) => {
    const prev = (store.get('applicationSettings')) || getDefaultApplicationSettings()
    const def = getDefaultApplicationSettings()

    let registerSuccess = false
    if (data.accelerator) {
      if (data.key === 'evokeChortcut') {
        // 唤醒
        registerSuccess = shortcuts.register(data.accelerator, () => {
          api.aiIconWindow.show()
          const appName = store.get('appName') || 'lightbox'
          const url = `${appName}://msgtype==showAiassistant&&show==true`;
          isProcessRunningWin(appName + '.exe').then(running => {
            if (running) {
              console.log('已启动')
              shell.openExternal(url);
            } else  {
              console.log('未启动')
            }
          });
        })
      } else if (data.key === 'screenshotChortcut') {
        // 截图
        registerSuccess = shortcuts.register(data.accelerator, () => {
          api.aiIconWindow.triggerScreenshot()
        })
      } else if (data.key === 'screenRecordingChortcut') {
        // 录屏
        registerSuccess = shortcuts.register(data.accelerator, () => {
          api.screenRecorderWindow.create()
        })
      } else if (data.key === 'chatChortcut') {
        // 问答
        registerSuccess = shortcuts.register(data.accelerator, () => {
          let isIntranet = false
          if (is.dev && process.env['ELECTRON_RENDERER_URL']) isIntranet =  true
          else isIntranet = store.get('isIntranet');
          if (true || isIntranet) {
            if (!api.aiChatWindow.isVisible()) {
              api.browserViewWindow.showBrowserView()
            }
          }
        })
      }
    }

    store.set('applicationSettings', {
      shortcuts: { ...def.shortcuts, ...prev.shortcuts, [data.key]: data.accelerator },
      recordingPath: prev.recordingPath || getDefaultApplicationSettings().recordingPath
    })

    if (registerSuccess) {
      if (prev.shortcuts && !prev.shortcuts['is' + data.key]) {
        const shortcutsObj = store.get('applicationSettings').shortcuts
        store.set('applicationSettings', {
          shortcuts: { ...shortcutsObj, ['is' + data.key]: true },
          recordingPath: prev.recordingPath || getDefaultApplicationSettings().recordingPath
        })
      }
    }

    return store.get('applicationSettings').shortcuts['is' + data.key]
  })
)

// 注销快捷键
routers.push(
  new EventRoute('unregister-single-shortcut', async (_api, { data }) => {
    shortcuts.unregister(data)
    return true
  })
)



export default routers
